package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.entity.Orders;
import com.itheima.entity.User;
import com.itheima.service.EmployeeService;
import com.itheima.service.OrdersService;
import com.itheima.service.UserService;
import com.itheima.util.SMSUtils2;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping("sendMsg")
    public R<String> login(@RequestBody User user,HttpServletRequest request){
        String phone = user.getPhone();

        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //SMSUtils2.sendMessage(phone,code);
        log.info("code:{}",code);

        //request.getSession().setAttribute("code",code);

        redisTemplate.opsForValue().set("code"+phone,code,2, TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpServletRequest request) {
        String phone = map.get("phone");
        String code = map.get("code");

        //String sessionCode = (String) request.getSession().getAttribute("code");

        String codeInSession =(String) redisTemplate.opsForValue().get("code" + phone);
        boolean flag = StringUtils.equals(code, codeInSession);
        if (!flag) {
            return R.error("验证码错误");
        }

        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null ) {
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        request.getSession().setAttribute("user",user.getId());

        redisTemplate.delete("code"+phone);
        return R.success(user);
    }
}
